package com.dxyxx.framework;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnStartListener;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Product;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ProductFragment extends BaseFragment {
	private final static String ID = "id";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS="imageIds";

	private List<String> msgs;
	private int pageId = -1;
	// private MyAdapter2 adapter;

	/** 总页数. */
	private int PageCount;
	/** 当前页码. */
	private int PageCurrent;
	/** 被选中的. */
	private int gridID = -1;
	/** 每页显示的数量，Adapter保持一致. */
	private static final float PAGE_SIZE = 12.0f;
	/** 自定义的左右滑动. */
	private ViewPager vp;
	/** 页码条布局. */

	/** 页码条. */
	private ImageView imgCur;
	// common private
	// private PullDownView commonView;

	private List<View> list;
	private String categoryName;
	private String categoryId;
	private int[] currentPage = { 1, 1, 1 }; // 当前加载页数

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View view = (ViewGroup) inflater.inflate(R.layout.activity_product, container, false);
		Bundle bundle = this.getArguments();
		categoryName = bundle.getString("categoryName");
		categoryId = bundle.getString("categoryId");
		initViews(view);
		setListView();
		return view;
	}

	/**
	 * 初始化
	 */
	private TextView commonText;
	private TextView privateText;
	private View commonTab;
	private View privateTab;
	private TextView otherText;
	private View otherTab;
	private Fragment self;

	private void initViews(View view) {
		self = this;
		ImageView backButton = ((ImageView) view.findViewById(R.id.backImageButton));
		backButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
				transaction.remove(self);
				transaction.commit();
			}
		});
		((ImageView) view.findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		TextView titleView = (TextView) view.findViewById(R.id.title);
		titleView.setText(categoryName);
		titleView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		list = new ArrayList<View>();
		vp = (ViewPager) view.findViewById(R.id.vp_message_launcher_layout);
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				setCurPage(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		commonText = (TextView) view.findViewById(R.id.commonText);
		commonText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (vp.getCurrentItem() != 0) {

					vp.setCurrentItem(0);
					System.out.println(vp.getCurrentItem());
				}
			}
		});
		privateText = (TextView) view.findViewById(R.id.privateText);
		privateText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (vp.getCurrentItem() != 1) {

					vp.setCurrentItem(1);
				}
			}
		});
		otherText = (TextView) view.findViewById(R.id.otherText);
		otherText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (vp.getCurrentItem() != 2) {

					vp.setCurrentItem(2);
				}
			}
		});
		commonTab = view.findViewById(R.id.commonTab);
		privateTab = view.findViewById(R.id.privateTab);
		otherTab = view.findViewById(R.id.otherTab);

	}

	/**
	 * 添加ListView
	 * 
	 */
	private ZrcListView[] listViews;
	private ViewGroup[] waitViewGroups;
	private MessageAdapter[] messageAdapters;
	private List<Map<String, String>>[] datas;

	// private View newestList;

	private void setListView() {
		listViews = new ZrcListView[3];
		waitViewGroups = new ViewGroup[3];
		messageAdapters = new MessageAdapter[3];
		datas = new List[3];
		// 在这里添加视图。多个自定义的View
		LayoutInflater mInflater = LayoutInflater.from(getActivity());
		for (int i = 0; i < 3; i++) {
			waitViewGroups[i] = (ViewGroup) mInflater.inflate(R.layout.fragment_wait, null);
			listViews[i] = (ZrcListView) mInflater.inflate(R.layout.component_product_listview, null);
			listViews[i].setDivider(getResources().getDrawable(R.color.common_list_devider_color));
			listViews[i].setDividerHeight(2);
			setStyle(listViews[i]);
			datas[i] = new ArrayList<Map<String, String>>();
			messageAdapters[i] = new MessageAdapter(getActivity(), datas[i]);
		}

		// listView = (ZrcListView) newestList.findViewById(R.id.zListView);

		String urlString = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT+"&order=newest";
		HttpUtil.get(urlString, new DownloadProductHandler(listViews[0], waitViewGroups[0], messageAdapters[0], 0, false));
		String urlString1 = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT+"&order=hot";
		HttpUtil.get(urlString1, new DownloadProductHandler(listViews[1], waitViewGroups[1], messageAdapters[1], 1, false));
		String urlString2 = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT+"&order=highprice";
		HttpUtil.get(urlString2, new DownloadProductHandler(listViews[2], waitViewGroups[2], messageAdapters[2], 2, false));

		for (int i = 0; i < 3; i++) {
			final int index = i;
			// 下拉刷新事件回调（可选）
			listViews[index].setOnRefreshStartListener(new OnStartListener() {
				@Override
				public void onStart() {

					refresh(index);
				}
			});

			// 加载更多事件回调（可选）
			listViews[index].setOnLoadMoreStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					loadMore(index);
				}
			});

		}

		for (ViewGroup temp : waitViewGroups) {
			list.add(temp);
		}
		vp.setAdapter(new MyAdapter());

	}

	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(list.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public void finishUpdate(View arg0) {
		}

	}

	// **设置listview 头部底部的样式
	private void setStyle(ZrcListView listView) {
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(getActivity());
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(getActivity());
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.topitem_in);
		listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 开启 加载更多多 的功能
		listView.startLoadMore();
	}

	/**
	 * 更新当前页码
	 */
	public void setCurPage(int page) {
		switch (page) {
		case 0:
			commonText.setTextColor(0xffFFD101);
			privateText.setTextColor(0xffcccccc);
			otherText.setTextColor(0xffcccccc);
			commonTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		case 1:
			privateText.setTextColor(0xffFFD101);
			commonText.setTextColor(0xffcccccc);
			otherText.setTextColor(0xffcccccc);
			privateTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		case 2:
			otherText.setTextColor(0xffFFD101);
			commonText.setTextColor(0xffcccccc);
			privateText.setTextColor(0xffcccccc);
			otherTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		default:
			break;
		}
	}

	// 异步下载信息
	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class MessageAdapter extends BaseAdapter {
		private List<Map<String, String>> data;

		public MessageAdapter(Context context, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;
		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		/*
		 * public MessageAdapter(Context context) { this.mInflater =
		 * LayoutInflater.from(context); }
		 */

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			holder = null;

			//int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				convertView = mInflater.inflate(R.layout.item_product_new, null);
				holder.descriptionText = (TextView) convertView.findViewById(R.id.description);
				holder.specificationText = (TextView) convertView.findViewById(R.id.specification);
				holder.priceText = (TextView) convertView.findViewById(R.id.price);
				holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumb);
				convertView.setTag(holder);
			}
			Map<String, String> map = this.data.get(position);

			holder = (ViewHolder) convertView.getTag();
			holder.descriptionText.setText(map.get(DESCRIPTION));
			holder.specificationText.setText(map.get(SPECIFICATION));
			holder.priceText.setText(map.get(PRICE));
			imageLoader.displayImage(map.get(THUMB), holder.thumbImage, squareOptions, animateFirstListener);

			convertView.setOnClickListener(new ItemClickListener(map));
			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	static class ViewHolder {
		public TextView descriptionText;
		public TextView specificationText;
		public TextView priceText;
		public ImageView thumbImage;
	}

	class ItemClickListener implements OnClickListener {
		private Map<String, String> map;

		public ItemClickListener(Map<String, String> map) {
			this.map = map;
		}

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(getActivity(), BuyProductActivity.class);

			// 用Bundle携带数据
			Bundle bundle = new Bundle();
			//传三个值 过去。
			bundle.putString(ID, map.get(ID));
			bundle.putString("categoryId", categoryId+"" );
			
			bundle.putString(DESCRIPTION, map.get(DESCRIPTION));
			bundle.putString(THUMB, map.get(THUMB));
			bundle.putString(IMAGEIDS, map.get(IMAGEIDS));
			bundle.putString(PRICE,map.get(PRICE));
			bundle.putString(SPECIFICATION,map.get(SPECIFICATION));
			intent.putExtras(bundle);

			startActivityForResult(intent, RequestCode.Product);
			 
		}
	}

	private void refresh(int index) {
		String urlString = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT;
		datas[index] = new ArrayList<Map<String, String>>();

		switch (index) {
		case 0:
			urlString = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT + "&order=newest";
			break;
		case 1:
			urlString = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT + "&order=hot";
			break;
		case 2:
			urlString = "product/list?categoryId=" + categoryId + "&current=1&count=" + COUNT + "&order=highprice";
			break;

		default:

			break;
		}
		HttpUtil.get(urlString, new DownloadProductHandler(listViews[index], waitViewGroups[index], messageAdapters[index], index, true));

		// adapter.notifyDataSetChanged();
		// listView1.setRefreshSuccess("加载成功"); // 通知加载成功
		// listView1.startLoadMore(); // 开启LoadingMore功能

	}

	private void loadMore(int index) {
		currentPage[index] = currentPage[index] + 1;
		String urlString = "product/list?categoryId=" + categoryId + "&current=" + currentPage[index] + "&count=" + COUNT;
		
		switch (index) {
		case 0:
			urlString = "product/list?categoryId=" + categoryId + "&current=" + currentPage[index] + "&count=" + COUNT+"&order=newest";
			break;
		case 1:
			urlString ="product/list?categoryId=" + categoryId + "&current=" + currentPage[index] + "&count=" + COUNT+"&order=hot" ;
			break;
		case 2:
			urlString="product/list?categoryId=" + categoryId + "&current=" + currentPage[index] + "&count=" + COUNT+"&order=highprice";
			break;

		default:
			 
			break;
		}
		
		HttpUtil.get(urlString, new DownloadMoreProductHandler(listViews[index], waitViewGroups[index], messageAdapters[index], datas[index]));

		// adapter.notifyDataSetChanged();
		// listView1.setLoadMoreSuccess("");

		// listView1.stopLoadMore();

	}

	// / 写一个通用的类。
	class DownloadProductHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		// private List<Map<String, String>> data;
		private int index;
		private boolean isRefresh;

		public DownloadProductHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, int index, boolean isRefresh) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			// this.data = data;
			this.index = index;
			this.messageAdapter = messageAdapter;
			this.isRefresh = isRefresh;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			listView.setRefreshSuccess("加载失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				JavaType type = getObjectMapper().getTypeFactory().constructCollectionType(List.class, Product.class);
				List<Product> products = getObjectMapper().readValue(new String(arg2), type);

				List<Map<String, String>> downloadData = new ArrayList<Map<String, String>>();
				for (Product product : products) {
					Map<String, String> map = new HashMap<String, String>();
					map.put(ID, product.getId()+"");
					map.put(DESCRIPTION, product.getDescription());
					map.put(PRICE, product.getPrice() + "");
					map.put(SPECIFICATION, product.getSpecification());
					map.put(THUMB, baseImageURL + product.getThumbId() + "?p=0");
					map.put(IMAGEIDS, product.getImageIds());
					downloadData.add(map);
				}
				// MessageAdapter adapter = new MessageAdapter(getActivity(),
				// data);
				datas[index].addAll(downloadData);
				if (!isRefresh) {

					listView.setAdapter(messageAdapter);
					// listView.refresh(); // 主动下拉刷新

					waitViewGroup.addView(listView);
				} else {
					// 刷新

					messageAdapter.data = datas[index];
					messageAdapter.notifyDataSetChanged();
					listView.setRefreshSuccess("加载成功"); // 通知加载成功

				}

			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// / 写一个通用的类。
	class DownloadMoreProductHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		private List<Map<String, String>> data;

		public DownloadMoreProductHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, List<Map<String, String>> data) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			this.data = data;
			this.messageAdapter = messageAdapter;

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			AgainPlayer.makeCall(getActivity(), "网络异常");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				JavaType type = getObjectMapper().getTypeFactory().constructCollectionType(List.class, Product.class);
				List<Product> products = getObjectMapper().readValue(new String(arg2), type);

				ArrayList<Map<String, String>> downloaddata = new ArrayList<Map<String, String>>();
				for (Product product : products) {
					Map<String, String> map = new HashMap<String, String>();
					map.put(ID, product.getId()+"");
					map.put(DESCRIPTION, product.getDescription());
					map.put(PRICE, product.getPrice() + "");
					map.put(SPECIFICATION, product.getSpecification());
					map.put(THUMB, baseImageURL + product.getThumbId() + "?p=0");
					map.put(IMAGEIDS, product.getImageIds());
					downloaddata.add(map);
				}
				// MessageAdapter adapter = new MessageAdapter(getActivity(),
				// data);
				if (downloaddata.size() == 0) {
					listView.stopLoadMore();
				} else {
					data.addAll(downloaddata);
					messageAdapter.notifyDataSetChanged();
					listView.setLoadMoreSuccess(); // 通知加载成功
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}